package com.tangye.massageshop.interceptors;

import com.alibaba.fastjson.JSON;
import com.tangye.massageshop.entity.UserEntity;
import com.tangye.massageshop.util.JwtUtil;
import com.tangye.massageshop.util.ThreadLocalUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Log4j2
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            UserEntity userEntity = JwtUtil.paresUserToken(token);
            log.info("Login User:{}", JSON.toJSONString(userEntity));
            ThreadLocalUtil.set(userEntity);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
